package models;

import models.constants.DeletedStatus;
import product.ProductSpec;
import util.common.UStringUtil;

import javax.persistence.*;
import java.util.List;

/**
 * Created by liming on 16/7/16.
 * 库存盘点明细
 */
@Entity
@Table(name = "admin_stock_taking_item")
public class AdminStockTakingItem extends BaseModel {

    /**
     * 库存盘点主表
     */
    @ManyToOne
    @JoinColumn(name = "admin_stock_taking")
    public AdminStockTaking adminStockTaking;

    /**
     * 选中的产品规格
     */
    @ManyToOne
    @JoinColumn(name = "product_spec")
    public ProductSpec productSpec;

    /**
     * 单价,注意要控制单价为0的产品不能进行库存盘点
     */
    @Column(name = "price")
    public Double price;

    /**
     * 系统库存数量
     */
    @Column(name = "sys_num")
    public Double sysNum;

    /**
     * 系统库存金额
     */
    @Column(name = "sys_amount")
    public Double sysAmount;

    /**
     * 实际库存数量
     */
    @Column(name = "actual_num")
    public Double actualNum;

    /**
     * 实际库存金额
     */
    @Column(name = "actual_amount")
    public Double actualAmount;

    /**
     * 盈亏数量
     */
    @Column(name = "diff_num")
    public Double diffNum;

    /**
     * 盈亏金额
     */
    @Column(name = "diff_amount")
    public Double diffAmount;

    /**
     * 备注
     */
    @Column(name = "remark")
    public String remark;


    /**
     * 查询同一库存盘点单下的产品集合
     * 查询主表adminStockTaking 的子表集合
     */
    public static List<AdminStockTakingItem> findStockTakingItemList(long id) {
        return AdminStockTakingItem.find("adminStockTaking.id=? and adminStockTaking.deletedStatus=?", id, DeletedStatus.UN_DELETED).fetch();
    }

    /**
     * 未生效的库存盘点单中,一种产品盘点记录只能出现一次
     * 检验在未生效的库存盘点中是否有重复盘点的产品
     * param insertStockTakingItemList
     */
    public static String auditStockTakingItem(List<Integer> insertIdList) {
        String str = "未生效的盘点单中:";
        String inserIds = UStringUtil.concatStr(",", insertIdList);
        List<AdminStockTakingItem> takingItemList = AdminStockTakingItem.find("adminStockTaking.auditUser = null and adminStockTaking.deletedStatus=? and productSpec.id in (" + inserIds + ")", DeletedStatus.UN_DELETED).fetch();
        if (takingItemList.size() > 0) {
            for (AdminStockTakingItem takingItem : takingItemList) {
                str += takingItem.productSpec.product.name + takingItem.productSpec.spec + ",";
            }
        }
        return str;
    }

    /**
     * 删除
     */
    public static void deleteItem(Integer[] delItemIdArray) {
        String delIdStr = UStringUtil.concatStr(",", delItemIdArray);
        AdminStockTakingItem.delete("id in (" + delIdStr + ")");
    }


}
